package com.espirit.eap.manager;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.espirit.eap.sa.Website;
import com.googlecode.cswish.exception.ApplicationException;
import com.googlecode.cswish.oosearch.QLInfo;
import com.googlecode.cswish.struts.spring.Executor;
import com.googlecode.cswish.struts.spring.GenericService;

@Service
@Transactional
public class CompanyService  {
	@Resource
	private SystemDataService systemDataService;

	@Resource
	GenericService genericService;
	
	private Company defaultCompany;
	
	public Company getCompany(){
		return genericService.load(getDefaultCompany());	
	}
	
	private Company getDefaultCompany(){
		if (defaultCompany == null){
			String hql = "select a from " + Company.class.getName() + " a order by a.id asc";
			QLInfo qlInfo = new QLInfo(hql, true);
			defaultCompany = (Company)genericService.searchByQl(qlInfo, false).getData(0);
		}
		return defaultCompany;
	}
	
	@Transactional
	public boolean deleteList(List<Company> results) {
    	boolean ret = true;
    	if (results != null) {
    		Company defaultCompany = getDefaultCompany();
			for (Company company : results) {
				if (company != null && company.getId() != null) {
					if (defaultCompany != null){
						if (defaultCompany.getId().equals(company.getId())){
							throw new ApplicationException(" cannt delete default company!");
						}
					} else {
						ret &= genericService.delete(company);
					}
				}
			}
		}
    	return ret;
	 }
	
	@Async
	public void changeDefaultCompanyName(){
		Company company = getDefaultCompany();
		if (company != null) {
			String name = genericService.executeInSite(Website.DEFAULT_NAME, new Executor<String, String>() {
				@Override
				public String execute(String parameters) {
					return systemDataService.getValue(SystemData.COMPANY_NAME);
				}
			}, null);
			if (name != null) {
				company.setName(name);
				genericService.merge(company);
			}
		}
	}
}
